package com.ben.chatroom.service;

import com.ben.chatroom.common.entity.ImNode;
import com.ben.chatroom.common.entity.ImUser;
import com.ben.chatroom.common.entity.LoginBack;
import com.ben.chatroom.common.result.Result;
import com.ben.chatroom.session.ClientSession;
import com.ben.chatroom.feignClient.WebOperator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author
 */
@Slf4j
@Service
public class CommandService {

  private int reConnectCount = 0;

  private Channel channel;
  private ClientSession session;

  private NettyClient nettyClient;

  public CommandService(NettyClient nettyClient) {
    this.nettyClient = nettyClient;
  }


  public Result<String> login(String userName, String pwd) {
    ImUser user = new ImUser();
    user.setUserName(userName);
    user.setToken(pwd);
    user.setDevId(UUID.randomUUID().toString());

    log.info("step1：开始登录WEB GATE");
    LoginBack loginBack = WebOperator.login(userName, pwd);

    List<ImNode> nodeList = loginBack.getImNodeList();

    log.info("step2：开始连接Netty 服务节点");

    if (nodeList.isEmpty()) {
      log.error("服务节点为空");
    } else {
      Collections.sort(nodeList);
    }

    nettyClient.setConnectedListener(connectedListener);
    for (ImNode imNode : nodeList) {



    }


    return null;
  }

  /**
   * 连接
   */
  GenericFutureListener<ChannelFuture> connectedListener = (ChannelFuture future) -> {
    final EventLoopGroup eventLoop = future.channel().eventLoop();

    if(!future.isSuccess() && ++reConnectCount < 3) {
      log.info("连接失败!,在10s之后准备尝试第{}次重连!", reConnectCount);
      eventLoop.schedule(
        () -> nettyClient.doConnect(),
        10,
        TimeUnit.SECONDS
      );
    }
    else if(future.isSuccess()) {
      log.info("服务器连接成功!");
      this.channel = future.channel();
      channel = future.channel();
      session = new ClientSession(channel);
      session.setConnected(true);


    }
    else {
      log.info("服务器多次连接失败!");
    }

  };

  GenericFutureListener<ChannelFuture> closeFuture = (ChannelFuture f) -> {
    channel = f.channel();
    ClientSession clientSession = channel.attr(ClientSession.SESSION_KEY).get();
    clientSession.close();

    log.info(new Date() + "断开连接!!!");

  };


}
